from flask import Blueprint, request
import _thread as thread
import base64
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading import Lock
import websocket
from PIL import Image
from socketIO import socketIO as socketio

# talkController 使用websocket与讯飞星火建立联系 使用socketio与前端建立联系
talkController = Blueprint('talkController',__name__)

# 保存图片位置
IMAGE_FLODER = './controller/LocalImage/'

# 询问的问题
question = ''
# 如果是图片理解 还会上传左右眼底图像
leftFilename = ''
rightFilename = ''

# 当前是哪个模型 取决于哪个连接
mode = 0

SocketThread = None
thread_lock = Lock()
answer = ''

# 与大模型正常对话 连接触发
@socketio.on('connect', namespace='/spark')
def chat_connect():
    print('namespace=talk连接成功')
    pass

@socketio.on('startTalk',namespace='/spark')
def imageUnderstand(data):
    global question,leftFilename,rightFilename
    question = data.get('question')
    leftFilename = data.get('leftFilename')
    rightFilename = data.get('rightFilename')

    # 连接成功 根据有无filename判断模式
    global mode
    if leftFilename == None or rightFilename == None:
        mode = 0
    else:
        mode = 1

    global SocketThread
    with thread_lock:
        if SocketThread is None:
            SocketThread = socketio.start_background_task(target=background_thread)

# 正常聊天 断开连接触发
@socketio.on('disconnect', namespace='/spark')
def disconnect_msg():
    print('正常对话连接断开!')

# 建立连接后的会运行的线程
def background_thread():
    try:
        cfg = config()
        appid = cfg["appid"]
        api_secret = cfg["api_secret"]
        api_key = cfg["api_key"]


        text = []
        text.clear()

        # 根据不同模式 输入不同请求连接和问题
        global mode
        Spark_url = ''
        domain = ''
        # 在这里会构建好用户问问题的格式
        if mode == 0:
            global question
            Spark_url = cfg["Spark_url"]
            domain = cfg["domain"]
            question = getText(question)
        if mode == 1:
            Spark_url = cfg["Image_spark_url"]
            domain = cfg["image_domain"]
            question = getImageUnderstand(question)
        startChat(appid, api_key, api_secret, Spark_url, domain, question)
    except Exception as e:
        print(e)

# websocket 后端与讯飞之间建立连接 需要鉴权
class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, Spark_url):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.host = urlparse(Spark_url).netloc
        self.path = urlparse(Spark_url).path
        self.Spark_url = Spark_url

    # 生成url
    def create_url(self):
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + self.host + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + self.path + " HTTP/1.1"

        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()

        signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'

        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": self.host
        }
        # 拼接鉴权参数，生成url
        url = self.Spark_url + '?' + urlencode(v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
        return url

# 收到websocket错误的处理
def on_error(ws, error):
    print("webSocket error:", error)

# 收到websocket关闭的处理
def on_close(ws, one, two):
    print("webSocket closed")

# 收到websocket连接建立的处理
def on_open(ws):
    thread.start_new_thread(run, (ws,))

# 收到websocket消息的处理
def on_message(ws, message):
    data = json.loads(message)
    code = data['header']['code']
    if code != 0:
        print(f'请求错误: {code}, {data}')
        ws.close()
    else:
        choices = data["payload"]["choices"]
        status = choices["status"]
        content = choices["text"][0]["content"]
        print(content, end="")
        socketio.emit('server_response',{"data": content},namespace='/spark')
        global answer
        answer += content
        if status == 2:
            global SocketThread
            socketio.emit('server_response', {"data": "[over]"}, namespace='/spark')
            SocketThread = None
            ws.close()

def run(ws, *args):
    data = json.dumps(gen_params(appid=ws.appid, domain=ws.domain, question=ws.question))
    ws.send(data)

def startChat(appid, api_key, api_secret, Spark_url, domain, question):
    wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()
    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
    ws.appid = appid
    ws.question = question
    ws.domain = domain
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

# 生成调用api所需的参数 按照api要求的来
def gen_params(appid, domain, question):
    """
    通过appid和用户的提问来生成请参数
    """
    data = {
        "header": {
            "app_id": appid,
            "uid": "721"
        },
        "parameter": {
            "chat": {
                "domain": domain,
                "temperature": 0.5,
                "max_tokens": 2048
            }
        },
        "payload": {
            "message": {
                "text": question
            }
        }
    }
    return data

# config配置类
def config():
    config = {}
    config["appid"] = "3c591f62"
    config["api_secret"] = "Y2M2YWU0N2QzOGE0ODcyMmY3ODgzMWY2"
    config["api_key"] = "14a25fc24a288e7c358a0e795275aa57"
    config["domain"] = "generalv3.5"
    config["Spark_url"] = "wss://spark-api.xf-yun.com/v3.5/chat"

    config["image_domain"] = "imagev3"
    config["Image_spark_url"] = "wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image"
    return config

def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length

def getText(content):
    text = []
    jsoncon = {}
    jsoncon["role"] = "user"
    jsoncon["content"] = content
    text.append(jsoncon)
    return text

def getImageUnderstand(content):
    text = []

    # 图片转base64
    global leftFilename,rightFilename
    leftFilePath = IMAGE_FLODER + leftFilename
    rightFilePath = IMAGE_FLODER + rightFilename

    # 左右眼拼一张图片
    left_img = Image.open(leftFilePath)
    left_img = left_img.resize((224, 224))
    right_img = Image.open(rightFilePath)
    right_img = right_img.resize((224, 224))

    combined_img = Image.new('RGB', (left_img.width + right_img.width, left_img.height))
    combined_img.paste(left_img, (0, 0))
    combined_img.paste(right_img, (left_img.width, 0))

    # 拼好后保存
    combined_save_path = IMAGE_FLODER + 'combined_img.jpg'
    combined_img.save(combined_save_path)

    # 转base64
    base64CombinedImage = return_img_stream(combined_save_path)

    imageJsoncon = {}
    imageJsoncon["role"] = "user"
    imageJsoncon["content"] = base64CombinedImage
    imageJsoncon["content_type"] = "image"
    textJsoncon = {}
    textJsoncon["role"] = "user"
    textJsoncon["content"] = content
    textJsoncon["content_type"] = "text"
    text.append(imageJsoncon)
    text.append(textJsoncon)
    return text

def return_img_stream(img_local_path):
    """
        工具函数:
        获取本地图片流
        :param img_local_path:文件单张图片的本地绝对路径
        :return: 图片流
        """
    img_stream = ''
    with open(img_local_path, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream).decode()
    return img_stream